<template>
  <el-button @click="handleAdd" plain type="primary" :icon="Plus">新增</el-button>
  <el-table v-loading="loading" :data="tableData" style="width: 100%; margin-top: 20px" row-key="id" border
            default-expand-all>
    <el-table-column prop="name" label="名称" min-width="150px"/>
    <el-table-column prop="type" label="类型">
      <template #default="scope">
        {{ scope.row.type == 1 ? '按钮' : '菜单' }}
      </template>
    </el-table-column>
    <el-table-column lable="操作" min-width="220px">
      <template #default="scope">
        <el-button link @click="handleEdit(scope.row,'add')" icon="plus" type="primary">新增</el-button>
        <el-button link @click="handleEdit(scope.row,'')" icon="Edit" type="primary">编辑</el-button>
        <el-button link @click="handleDel(scope.row)" icon="Delete" type="primary">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <MenuDialog ref="menuDialog" @saveSuccess="getData" :dialog-visible="dialogVisible"
              @closeDialog="dialogVisible = false"/>
</template>

<script setup>
import {ref, onBeforeMount, nextTick} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus';
import {Plus, Edit, Delete} from '@element-plus/icons-vue'
import MenuDialog from './MenuDialog.vue'
import {getMenuList, menuTreeDel} from '@/api/menu/index'

let dialogVisible = ref(false)
const loading = ref(false)
const menuDialog = ref(null)
let tableData = ref([])

let getData = async () => {
  loading.value = true
  let data = await getMenuList();
  loading.value = false
  tableData.value = data.data.list
  console.log('tableData', tableData)
}

const handleEdit = (row, type) => {
  console.log(row);
  dialogVisible.value = true
  row.pid = row.pid + ''
  nextTick(() => {
    if (type === 'add') {
      menuDialog.value.form = Object.assign(menuDialog.value.form, {pid: row.id + ''})
    } else {
      if (row.type !== 1) {
        let pathArray = []
        if (typeof row.path === 'string') {
          row.path = row.path.split('/')
          row.path.forEach(item => {
            if (item) {
              pathArray.push(item)
            }
          });
          pathArray[0] = '/' + pathArray[0]
          row.path = pathArray
          console.log(pathArray)
        }
      }
      menuDialog.value.form = Object.assign(menuDialog.value.form, row)
    }

  })
}

const handleAdd = () => {
  dialogVisible.value = true
}

const handleDel = (row) => {
  ElMessageBox.confirm('确认要删除 ? 一旦删除无法恢复', '提示', {type: 'warning'}).then(async () => {
    let res = await menuTreeDel({id: row.id})
    if (res) {
      ElMessage({message: '删除成功', type: 'success'})
      getData();
    }
  }).catch(() => {

  })
}

onBeforeMount(() => {
  getData()
})
</script>
<style scoped></style>
